<template>
    <div class="user-list-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-input v-model="searchUsername" placeholder="请输入用户名" style="width: 200px;" />
            <el-select v-model="searchIsValid" placeholder="请选择是否有效" style="width: 200px;">
                <el-option label="有效" value="1" />
                <el-option label="无效" value="0" />
            </el-select>
            <el-button @click="searchUsers" type="success" style="width: 10%;" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetSearch" type="info" style="width: 10%;" icon="el-icon-delete">重置</el-button>
        </div>

        <!-- 操作按钮区域 -->
        <div class="add-user-area">
            <el-button @click="openDialog('add')" type="primary" style="width: 150px; margin-bottom: 50px;"
                icon="el-icon-user-solid">新增用户</el-button>
            <el-button @click="openUploadDialog" type="primary" style="width: 150px; margin-bottom: 50px;"
                icon="el-icon-picture">上传头像</el-button>
        </div>

        <!-- 用户列表区域 -->
        <el-table :data="userList" stripe border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userName" label="用户名" width="130"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="130"></el-table-column>
            <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="openDialog('detail', scope.row)" type="success"
                        style="width: 100px; text-align: center;" icon="el-icon-link">查看详情</el-button>
                    <el-button @click="openDialog('edit', scope.row)" type="primary"
                        style="width: 100px; text-align: center;" icon="el-icon-edit">修改用户</el-button>
                    <el-button @click="handleResetPwd(scope.row.userId)" type="danger"
                        v-if="scope.row.userId !== adminUserId" style="width: 100px; text-align: center;"
                        icon="el-icon-refresh">重置密码</el-button>
                    <el-button @click="handleDeleteUser(scope.row.userId)" type="danger"
                        v-if="scope.row.userId !== adminUserId" style="width: 100px; text-align: center;"
                        icon="el-icon-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 上传头像弹窗 -->
        <el-dialog :visible.sync="uploadDialogVisible" title="上传头像" custom-class="upload-dialog">
            <el-upload class="avatar-uploader" action="http://localhost:8080/shopping/user/upload"
                :show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                :before-upload="beforeAvatarUpload" :data="uploadData">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="uploadDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <!-- 统一弹窗 -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" custom-class="add-user-dialog"
            :show-close="false">
            <el-form :model="formUser" ref="userForm" label-width="100px" :disabled="dialogMode === 'detail'">
                <el-form-item label="用户名">
                    <el-input v-model="formUser.userName" />
                </el-form-item>
                <el-form-item label="密码" v-if="dialogMode === 'add'">
                    <el-input v-model="formUser.pwd" type="password" />
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="formUser.nickName" />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="formUser.email" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="formUser.phone" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="formUser.gender">
                        <el-option label="男" value="1" />
                        <el-option label="女" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否有效">
                    <el-select v-model="formUser.isValid">
                        <el-option label="是" value="1" />
                        <el-option label="否" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属角色">
                    <el-select v-model="formUser.roleId" placeholder="请选择角色">
                        <el-option v-for="role in roles" :key="role.roleId" :label="role.roleName"
                            :value="role.roleId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-if="dialogMode !== 'detail'" type="primary" @click="submitForm"
                        style="width: 100px;">确定</el-button>
                    <el-button type="warn" icon="el-icon-delete" @click="dialogVisible = false"
                        style="width: 100px;">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            // 搜索参数
            searchUsername: '',
            searchIsValid: '1',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            // 用户列表
            userList: [],
            // 角色数据
            roles: [],
            // 弹窗相关
            dialogVisible: false,
            dialogMode: '',
            dialogTitle: '',
            formUser: {
                userId: null,
                userName: '',
                pwd: '',
                nickName: '',
                email: '',
                phone: '',
                gender: '1',
                isValid: '1',
                roleId: null
            },
            // 管理员用户ID
            adminUserId: null,
            // 上传相关
            uploadDialogVisible: false,
            selectedUsers: [],
            imageUrl: '',
            uploadData: {}
        };
    },
    methods: {
        // 搜索用户列表
        searchUsers() {
            axios.get('http://localhost:8080/shopping/user/list', {
                params: {
                    userName: this.searchUsername,
                    isValid: this.searchIsValid,
                    currentPage: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(response => {
                this.userList = response.data.data.records;
                this.total = response.data.data.total;
                // 更新管理员ID
                this.adminUserId = this.userList.find(user => user.userName === 'admin')?.userId || null;
            }).catch(error => {
                console.error(error);
            });
        },
        // 获取所有角色信息 -- 供统一弹窗使用 -- 展示角色名
        searchRoles() {
            axios.get('http://localhost:8080/shopping/role/all').then(response => {
                this.roles = response.data.data;
            }).catch(error => {
                console.error(error);
            });
        },
        // 重置搜索
        resetSearch() {
            this.searchUsername = '';
            this.searchIsValid = '1';
            this.currentPage = 1;
            this.searchUsers();
        },

        // 打开弹窗
        openDialog(mode, user = null) {
            this.dialogMode = mode;
            this.dialogVisible = true;
            if (mode === 'add') {
                this.dialogTitle = '新增用户';
                this.formUser = {
                    userId: null,
                    userName: '',
                    pwd: '',
                    nickName: '',
                    email: '',
                    phone: '',
                    gender: '1',
                    isValid: '1',
                    roleId: null
                };
            } else {
                axios.get('http://localhost:8080/shopping/user/detail', {
                    params: {userId: user.userId}
                }).then(response => {
                    const userDb = response.data.data;
                    this.dialogTitle = mode === 'edit' ? '修改用户' : '用户详情';
                    this.formUser = {
                        userId: userDb.userId,
                        userName: userDb.userName,
                        pwd: userDb.pwd,
                        nickName: userDb.nickName,
                        email: userDb.email,
                        phone: userDb.phone,
                        gender: userDb.gender.toString(),
                        isValid: userDb.isValid.toString(),
                        roleId: userDb.roleId
                    }
                })
            }
            // 重置表单
            this.$nextTick(() => {
                this.$refs.userForm?.resetFields();
            });
        },
        // 提交表单
        submitForm() {
            this.$refs.userForm.validate((valid) => {
                if (valid) {
                    const payload = {
                        ...this.formUser,
                        isValid: parseInt(this.formUser.isValid)
                    };
                    const loading = this.$loading({
                        lock: true,
                        text: "提交中...",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)"
                    });
                    // 根据模式选择请求方法
                    const method = this.dialogMode === 'edit' ? 'put' : 'post';
                    const url = this.dialogMode === 'edit'
                        ? `http://localhost:8080/shopping/user/edit`
                        : 'http://localhost:8080/shopping/user/add';
                    axios[method](url, payload).then(response => {
                        loading.close();
                        if (response.data.code === 200) {
                            this.$message.success(`${this.dialogMode === 'edit' ? '修改' : '新增'}用户成功`);
                            this.dialogVisible = false;
                            this.searchUsers();
                        } else {
                            this.$message.error(response.data.message || '操作失败');
                        }
                    }).catch(error => {
                        loading.close();
                        this.$message.error('网络错误，请重试:' + error);
                    });
                }
            });
        },

        // 重置密码（带确认框）
        handleResetPwd(userId) {
            this.$confirm('确认重置该用户的密码吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.resetPwd(userId);
            }).catch(() => {
                this.$message.info('已取消重置');
            });
        },
        // 重置密码
        resetPwd(userId) {
            axios.get('http://localhost:8080/shopping/user/reset', {
                params: { userId }
            }).then(response => {
                if (response.data.code === 200) {
                    this.$message.success('密码已重置为：' + response.data.data);
                } else {
                    this.$message.error('重置密码失败');
                }
            }).catch(error => {
                console.error(error);
            });
        },

        // 删除用户（带确认框）
        handleDeleteUser(userId) {
            this.$confirm('确认删除该用户吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteUser(userId);
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        // 删除用户
        deleteUser(userId) {
            axios.delete(`http://localhost:8080/shopping/user/del`, {
                params: { userId }
            }).then(response => {
                if (response.data.code === 200) {
                    this.$message.success('删除用户成功');
                    this.searchUsers();
                } else {
                    this.$message.error(response.data.message);
                }
            }).catch(error => {
                console.error(error);
            });
        },

        // 处理分页变化
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.searchUsers();
        },
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.searchUsers();
        },

        // 处理多选变化
        handleSelectionChange(selection) {
            this.selectedUsers = selection.map(user => user.userId);
        },
        // 打开上传对话框
        openUploadDialog() {
            if (this.selectedUsers.length === 0) {
                this.$message.warning('请先选择要上传头像的用户');
                return;
            }
            if (this.selectedUsers.length > 1) {
                this.$message.warning('只能选择一个用户上传头像');
                return;
            }
            this.uploadData.userId = this.selectedUsers[0];
            this.uploadDialogVisible = true;
        },
        // 文件上传前验证
        beforeAvatarUpload(file) {
            const isJPGOrPNG = (file.type === 'image/jpeg' || file.type === 'image/png');
            const isLt5GB = file.size / 1024 / 1024 < 5 * 1024; // 5GB = 5*1024MB
            if (!isJPGOrPNG) {
                this.$message.error('只能上传JPG/PNG格式的图片');
                return false;
            }
            if (!isLt5GB) {
                this.$message.error('文件大小不能超过5GB');
                return false;
            }
            return true;
        },
        // 上传成功处理
        handleUploadSuccess(response) {
            var avatarPath = response.data
            localStorage.setItem('avatarPath', avatarPath);
            this.$message.success('头像上传成功' + avatarPath);
            this.uploadDialogVisible = false;
            this.searchUsers(); // 刷新列表
        },
        // 上传失败处理
        handleUploadError(err) {
            this.$message.error('头像上传失败，请检查网络或文件格式');
            console.error(err);
        }
    },
    mounted() {
        this.searchUsers();
        this.searchRoles();
    }
};
</script>

<style scoped>
.user-list-container {
    padding: 20px;
}

.search-area {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.search-area .el-input {
    margin-right: 10px;
}

.search-area .el-select {
    margin-right: 10px;
}

.search-area .el-button {
    margin-right: 10px;
}

.el-button {
    height: 40px;
    margin-top: -12px;
}

.add-user-area {
    margin-bottom: 20px;
}

.add-user-dialog {
    width: 500px;

    .el-dialog__header {
        background-color: #f0f9eb;
        border-bottom: 1px solid #e5e5e5;
        padding: 15px;
    }

    .el-dialog__title {
        color: #67c23a;
        font-size: 18px;
    }

    .el-dialog__body {
        padding: 20px;
    }

    .el-dialog__footer {
        border-top: 1px solid #e5e5e5;
        padding: 15px;
        text-align: right;
    }
}

.upload-dialog {
    width: 500px;

    .avatar-uploader {
        display: inline-block;
        margin: 20px;
    }

    .avatar {
        width: 128px;
        height: 128px;
        border-radius: 50%;
        vertical-align: middle;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #999;
        width: 128px;
        height: 128px;
        line-height: 128px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 50%;
        vertical-align: middle;
    }
}
</style>